package com.example.dell.newstart.type;

import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import android.widget.LinearLayout;
import android.widget.TextView;


import com.example.dell.newstart.MainActivity;
import com.example.dell.newstart.R;
import com.example.dell.newstart.base.BaseActivity;
import com.example.dell.newstart.base.RequestInterface;
import com.example.dell.newstart.base.ServerResponse;
import com.example.dell.newstart.bean.MyPageInfo;
import com.example.dell.newstart.bean.Product;

import java.util.ArrayList;
import java.util.List;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * created by Dongkai on 2018/12/12
 */

public class ProductListActivity extends BaseActivity {
    @BindView(R.id.erv_product)
    RecyclerView ervProduct;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_home)
    TextView tvHome;

    private List<Product> productList = new ArrayList<>();//产品的列表

    private int CURRENT_TYPE;//记录传过来的产品类别id
    private ProductAdapter productAdapter;//我们自定义的适配器

    private int currentPage = 1;//记录当前页，用于分页加载


    @Override
    public int initLayout() {
        /**
         * 获取从{@link TypeFragment} 传过来的intent
         */
        Intent intent = getIntent();
        //从intent当中获取传过来的类别
        CURRENT_TYPE = intent.getIntExtra("categoryID", 10006);
        //根据类别id请求数据
        String keyword = intent.getStringExtra("keywords");

        if (!TextUtils.isEmpty(keyword)) {
            //在关键词不为空的情况下，根据关键词进行搜索
            sendGetProductsByKeywords(keyword);
        } else {
            //在关键词为空的情况下，根据产品类别搜索搜索
            sendGetProductsByTypeRequest(CURRENT_TYPE);
        }

        return R.layout.activity_product_list;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        int colorId = getResources().getColor(R.color.divider_decoration);
        //分隔线
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        ervProduct.addItemDecoration(dividerItemDecoration);
        //获得一个线性布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ProductListActivity.this);
        //设置布局管理器
        ervProduct.setLayoutManager(linearLayoutManager);

        productAdapter = new ProductAdapter(this, productList);
        ervProduct.setAdapter(productAdapter);

    }

    @Override
    public void initData() {
        tvTitle.setText("商品专区");
    }

    //根据产品类别请求网络数据
    private void sendGetProductsByTypeRequest(int categoryId) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.getProductsList2 getProductsList = retrofit.create(RequestInterface.getProductsList2.class);

        Call<ServerResponse<MyPageInfo<Product>>> call = getProductsList.getProducts("", CURRENT_TYPE, currentPage, 8, "");

        call.enqueue(new Callback<ServerResponse<MyPageInfo<Product>>>() {

            @Override
            public void onResponse(Call<ServerResponse<MyPageInfo<Product>>> call, Response<ServerResponse<MyPageInfo<Product>>> response) {
//                Log.d(TAG, "onResponse: " + response.body().getData());
                //获取返回的数据（就是ServerResponse<T>中的T代表的东西）
                if (response.body() == null) {
                    toastShort("数据加载出错，请检查服务器资源！");
                    return;
                }
                MyPageInfo<Product> pageInfo = response.body().getData();
                currentPage = pageInfo.getPageNum();
                //在PageInfo中通过list获取到产品的集合（多个product对象）
                productList = pageInfo.getList();
                //循环遍历，通过log输出产品信息
                /*for (Product product : productList) {
                    Log.d(TAG, "onResponse: ####product#######" + product.toString());
                }*/
              /*  //获取我们列表的适配器，传入context和productList参数
                productAdapter = new ProductAdapter(ProductListActivity.this, productList);
                //给列表设置适配器
                ervProduct.setAdapter(productAdapter);*/
                productAdapter.addAll(productList);

            }

            @Override
            public void onFailure(Call<ServerResponse<MyPageInfo<Product>>> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
                toastShort("请求产品失败，请求的类别id是：" + CURRENT_TYPE);
            }
        });
    }

    //根据产品类别请求网络数据
    private void sendGetProductsByKeywords(String keyword) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.getProductsList2 getProductsList = retrofit.create(RequestInterface.getProductsList2.class);

        Call<ServerResponse<MyPageInfo<Product>>> call = getProductsList.getProducts(keyword, null, 1, 8, "");

        call.enqueue(new Callback<ServerResponse<MyPageInfo<Product>>>() {

            @Override
            public void onResponse(Call<ServerResponse<MyPageInfo<Product>>> call, Response<ServerResponse<MyPageInfo<Product>>> response) {
//                Log.d(TAG, "onResponse: " + response.body().getData());
                //获取返回的数据（就是ServerResponse<T>中的T代表的东西）
                MyPageInfo<Product> pageInfo = response.body().getData();
                //在PageInfo中通过list获取到产品的集合（多个product对象）
                productList = pageInfo.getList();
                //循环遍历，通过log输出产品信息
                /*for (Product product : productList) {
                    Log.d(TAG, "onResponse: ####product#######" + product.toString());
                }*/
               /* //获取我们列表的适配器，传入context和productList参数
                productAdapter = new ProductAdapter(ProductListActivity.this, productList);
                //给列表设置适配器
                ervProduct.setAdapter(productAdapter);*/
                productAdapter.addAll(productList);
            }

            @Override
            public void onFailure(Call<ServerResponse<MyPageInfo<Product>>> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
                toastShort("请求产品失败，请求的类别id是：" + CURRENT_TYPE);
            }
        });
    }

    @OnClick({R.id.ll_back, R.id.tv_home})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_home:
                goNextActivity(MainActivity.class);
                finish();
                break;
        }
    }
}
